package cn.cn77.futures;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import cn.cn77.futures.utils.C2Sever;
import cn.cn77.futures.utils.MyApplication;
import cn.cn77.futures.utils.UserSharedPreference;
import cn.cn77.futures.utils.Utils;
import cn.cn77.futures.widget.NavigationBar;

/**
 * @author 振朝 新建产品页面
 */
public class NewProductActivity extends BaseActivity {
	private static final String DelString = "已删除";
	private NavigationBar naviBar;
	private TextView delBt;
	private ListView productLv;
	private SimpleAdapter mAdapter;
	private ArrayList<HashMap<String, String>> listData = new ArrayList<HashMap<String, String>>();
	/**
	 * ListView模板中数据显示组件表
	 */
	private int[] items = { R.id.tv_times, R.id.tv_time, R.id.tv_state };
	/**
	 * ListView模版中数据key表
	 */
	private String[] fields = { "times", "time", "operation" };
	private int times = 1;
	private String mOperationCode;
	private String productId;
	/**
	 * 判断当前环境是否适合播放铃声
	 */
	private boolean shouldPlayBeep = true;
	private MediaPlayer mediaPlayer;
	AudioManager audioService;
	private boolean isLongPress = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_product_activity);
		MyApplication.getInstance().addActivity(this);
		naviBar = (NavigationBar) findViewById(R.id.new_product_navi_bar);
		naviBar.setTitle("新建产品");
		delBt = (TextView) findViewById(R.id.shanchu_tv);
		productLv = (ListView) findViewById(R.id.lv_product);
		setUrl(C2Sever.Controller.NewProduct, C2Sever.Action.NewProduct);
		mParams.put("mid", UserSharedPreference.getParams(
				UserSharedPreference.USER_ID, this));
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
	}

	private void initRinger() {
		audioService = (AudioManager) this
				.getSystemService(Context.AUDIO_SERVICE);
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mediaPlayer
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer player) {
						player.seekTo(0);
					}
				});
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			shouldPlayBeep = false;
		}
	}

	/**
	 * 准备声音
	 * 
	 * @param audioId
	 * @return
	 */
	private void prepareRinger(int audioId) {
		initRinger();
		AssetFileDescriptor file = this.getResources().openRawResourceFd(
				audioId);
		try {
			mediaPlayer.setDataSource(file.getFileDescriptor(),
					file.getStartOffset(), file.getLength());
			file.close();
			mediaPlayer.setVolume(5000, 5000);
			mediaPlayer.prepare();
		} catch (IOException ioe) {
			Log.w("播放声音", ioe);
			mediaPlayer = null;
		}
	}

	private void upRinger(String vibCode) {
		if (!"01".equals(vibCode)) {
			prepareRinger(R.raw.up);
			if (mediaPlayer != null && shouldPlayBeep) {
				mediaPlayer.start();
			}
		}
	}

	private void downRinger(String vibCode) {
		if (!"01".equals(vibCode)) {
			prepareRinger(R.raw.down);
			if (mediaPlayer != null && shouldPlayBeep) {
				mediaPlayer.start();
			}
		}
	}

	private void noticeRinger(String vibCode) {
		if ("01".equals(vibCode)) {
			prepareRinger(R.raw.notice);
			if (mediaPlayer != null && shouldPlayBeep) {
				mediaPlayer.start();
			}
		}
	}

	private void delRinger() {
		prepareRinger(R.raw.del);
		if (mediaPlayer != null && shouldPlayBeep) {
			mediaPlayer.start();
		}
	}

	/**
	 * 执行操作 每执行一次操作， 在list添加一条数据之后，判断数据长度是否大于3 大于3则 list remove 第一个 add 最后一个
	 * 
	 * @param status
	 * @param string
	 */
	private void doOperation(String operationCode, int status) {
		mOperationCode = operationCode;
		if ("close".equals(operationCode)) {
			mParams.put(C2Sever.Field.NewProduct.EndTime,
					Utils.getCurrentTime("HH:mm:ss"));
		}
		mParams.put(C2Sever.Field.NewProduct.Operation, operationCode);

		if (null == productId) {
			productId = "0";
		}
		mParams.put(C2Sever.Field.NewProduct.ProuductId, productId);
		String timeStamp = UserSharedPreference.getParams(
				UserSharedPreference.TimeStamp, this);
		UserId = UserSharedPreference.getParams(UserSharedPreference.USER_ID,
				this);
		String postCode = Utils.postCode(UserId, timeStamp);
		mParams.put(C2Sever.Field.Uid, UserId);
		mParams.put(C2Sever.Field.PostCode, postCode);
		doAsyncPost(this, status);
	}

	/**
	 * 操作成功后，将数据刷新列表
	 */
	private void freshView(String vibCode) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(fields[0], "第" + (times++) + "次");

		map.put(fields[1], Utils.getCurrentTime("HH:mm:ss"));
		String successLabel = "";
		if ("01".equals(vibCode))
			successLabel = "√";
		switch (mOperationCode) {
		case "1":
			map.put(fields[2], "乘" + successLabel);
			break;
		case "-1":
			map.put(fields[2], "除" + successLabel);
			break;
		case "del":
			map.put(fields[2], DelString + successLabel);
			break;
		default:
			break;
		}
		listData.add(0, map);
		if (listData.size() > 3) {
			listData.remove(listData.size() - 1);
		}
		mAdapter = new SimpleAdapter(this, listData, R.layout.new_product_item,
				fields, items);
		productLv.setAdapter(mAdapter);
	}

	@Override
	protected void successWithData(JSONObject data, int status) {
		try {
			JSONObject o = data.getJSONObject(C2Sever.Field.Other);
			productId = o.getString(C2Sever.Field.NewProduct.ProuductId);
			String vibCode = o.getString(C2Sever.Field.NewProduct.Vibrator);
			Log.i("pid", "接收" + productId);
			noticeRinger(vibCode);
			switch (status) {
			case 0:
				upRinger(vibCode);
				doVibratorBy(vibCode);
				break;
			case 1:
				downRinger(vibCode);
				doVibratorBy(vibCode);
				break;
			case 2:
				delRinger();
				break;
			default:
				break;
			}

			doVibratorBy(o.getString(C2Sever.Field.NewProduct.Vibrator));
			freshView(vibCode);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void failureTest(JSONObject o, int status) {
		try {
			showToast(o.getString(C2Sever.Field.Message));
			switch (status) {
			case 0:
				upRinger("00");
				break;
			case 1:
				downRinger("00");
				break;
			case 2:
				delRinger();
				break;
			default:
				break;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据带有zd数据的JSONObject数据进行振动
	 * 
	 * @param o
	 * @throws JSONException
	 */
	private void doVibratorBy(String vibratorCode) throws JSONException {

		switch (vibratorCode) {
		case "00":
			vibrator.vibrate(300);
			break;
		case "01":
			vibrator.vibrate(1000);
			break;
		default:
			Log.i("网络操作", "振动代码无效");
			break;
		}
	}

	/**
	 * 底部操作栏按钮监听
	 * 
	 * @param v
	 */
	public void operation(View v) {
		switch (v.getId()) {
		case R.id.zhang_tv:
			doOperation("1", 0);
			delBt.setBackgroundColor(this.getResources().getColor(
					R.color.android_red));
			delBt.setClickable(true);
			break;
		case R.id.die_tv:
			doOperation("-1", 1);
			delBt.setBackgroundColor(this.getResources().getColor(
					R.color.android_red));
			delBt.setClickable(true);
			break;
		case R.id.shanchu_tv:
			delBt.setBackgroundColor(this.getResources().getColor(
					R.color.second_gray));
			delBt.setClickable(false);
			doOperation("del", 2);
			break;
		case R.id.guanbi_tv:
			showShutDownDialog();
			break;
		default:
			break;
		}
	}

	private void showShutDownDialog() {
		DialogListener listener = new DialogListener();
		new AlertDialog.Builder(this).setTitle("关闭本产品")
				.setNegativeButton("关闭", listener)
				.setPositiveButton("返回", listener).create().show();
	}

	/**
	 * 对话框的监听类
	 * 
	 * @author 振朝
	 */
	private class DialogListener implements DialogInterface.OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			Log.i("dialog", "" + which);
			switch (which) {
			case -2:
				doOperation("close", 3);
				finish();
				break;
			case -1:
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 手机音量控制涨跌
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.i("网络操作", "onKeyDown");
		event.startTracking();
		if (event.getRepeatCount() == 0) {
			isLongPress = false;
			return true;
		}
		return true;
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (!isLongPress) {
			Log.i("网络操作", "onKeyUp");
			switch (keyCode) {
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				doOperation("-1", 1);
				delBt.setBackgroundColor(this.getResources().getColor(
						R.color.android_red));
				delBt.setClickable(true);
				Log.i("网络操作", "音量减");
				return true;
			case KeyEvent.KEYCODE_VOLUME_UP:
				doOperation("1", 0);
				delBt.setBackgroundColor(this.getResources().getColor(
						R.color.android_red));
				delBt.setClickable(true);
				Log.i("网络操作", "音量加");
				return true;
			default:
				break;
			}
		}
		return super.onKeyUp(keyCode, event);
	}

	/**
	 * 长按操作
	 */
	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		Log.i("网络操作", "onKeyLongPress");

		switch (keyCode) {
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			doOperation("-1", 1);
			delBt.setBackgroundColor(this.getResources().getColor(
					R.color.android_red));
			delBt.setClickable(true);
			Log.i("网络操作", "长按音量减");
			isLongPress = true;
			return true;
		case KeyEvent.KEYCODE_VOLUME_UP:
			doOperation("1", 0);
			delBt.setBackgroundColor(this.getResources().getColor(
					R.color.android_red));
			delBt.setClickable(true);
			isLongPress = true;
			Log.i("网络操作", "长按音量加");
			return true;
		default:
			break;
		}
		return true;
	}

}
